package landyer.study.charsetdetect;

import org.apache.commons.io.FileUtils;
import org.mozilla.intl.chardet.nsDetector;
import org.mozilla.intl.chardet.nsICharsetDetectionObserver;
import org.mozilla.intl.chardet.nsPSMDetector;

import java.io.*;
import java.nio.charset.Charset;
import java.util.Arrays;

/**
 * @author xddai
 */
public class CharsetDetector {

    private boolean found = false;
    private String result;
    private int lang;

    public String[] detectChineseCharset(InputStream in) throws IOException {
        lang = nsPSMDetector.CHINESE;
        String[] prob;
        // Initalize the nsDetector() ;
        nsDetector det = new nsDetector(lang);
        // Set an observer...
        // The Notify() will be called when a matching charset is found.

        det.Init(new nsICharsetDetectionObserver() {

            public void Notify(String charset) {
                found = true;
                result = charset;
            }
        });
        BufferedInputStream imp = new BufferedInputStream(in);
        byte[] buf = new byte[1024];
        int len;
        boolean isAscii = true;
        while ((len = imp.read(buf, 0, buf.length)) != -1) {
            // Check if the stream is only ascii.
            if (isAscii)
                isAscii = det.isAscii(buf, len);
            // DoIt if non-ascii and not done yet.
            if (!isAscii) {
                if (det.DoIt(buf, len, false))
                    break;
            }
        }
        imp.close();
        in.close();
        det.DataEnd();
        if (isAscii) {
            found = true;
            prob = new String[]
                    {
                            "ASCII"
                    };
        } else if (found) {
            prob = new String[]
                    {
                            result
                    };
        } else {
            prob = det.getProbableCharsets();
        }
        return prob;
    }

    public String[] detectAllCharset(InputStream in) throws IOException {
        try {
            lang = nsPSMDetector.ALL;
            return detectChineseCharset(in);
        } catch (IOException e) {
            throw e;
        }
    }

    public Charset detectOneCharset(InputStream in) throws IOException {
        String one = detectChineseCharset(in)[0];
        return Charset.forName(one);
    }

    public boolean isBom(FileInputStream fileInputStream) throws IOException {
       /* InputStreamReader reader = new InputStreamReader(fileInputStream, "utf8");
        int firstChar = reader.read();
        reader.close();
        return firstChar == 0xfeff;*/
        byte[] utf8Bom = new byte[3];
        fileInputStream.read(utf8Bom);
        fileInputStream.close();
        if(-17 == utf8Bom[0] && -69 == utf8Bom[1] && -65 ==utf8Bom[2]){
            return true;
        }
        return false;
    }

    public void removeBom(File poll) throws IOException {
        byte[] content = FileUtils.readFileToByteArray(poll);
        byte[] newContent = Arrays.copyOfRange(content, 3, content.length);
        FileUtils.writeByteArrayToFile(poll, newContent, false);
    }
    /*public boolean isBom(FileInputStream fileInputStream) throws IOException {
        byte[] buf = new byte[3];
        fileInputStream.read(buf);
        fileInputStream.close();
        return buf[0] == 0xef && buf[1] == 0xbb && buf[2] == 0xbf;
    }*/
}